package LinkedList;

import java.util.HashSet;
import java.util.Set;

public class _817_LinkedListComponents {
    public int numComponents(ListNode head, int[] G) {
        Set<Integer> sets = new HashSet<>();
        int res = 0;
        for (int i = 0; i < G.length; i++) {
            sets.add(G[i]);
        }
        ListNode p = head;
        while (p != null) {
            if (sets.contains(p.val) && (p.next == null || sets.contains(p.next.val))) {
                res++;
                p = p.next;
            }
        }
        return res;
    }
}
